import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Entry from './views/Entry.vue'
import store from './store'

Vue.use(Router)


if(localStorage.getItem('token')) {
  store.commit('setToken', localStorage.getItem('token'))
}

// if(localStorage.getItem('userInfo')) {
//   store.commit('setUserInfo', localStorage.getItem('userInfo'))
// }

const router = new Router({
  routes: [
    {
      name: 'a',
      path: '/',
      component: Entry,
      redirect: '/home',
      children: [
        {
          path: 'home',
          component: () => import(/* webpackChunkName: "home" */ './views/Home.vue'),
        },{
          path: 'classify',
          component: () => import(/* webpackChunkName: "home" */ './views/Home.vue'),
        },{
          path: 'cart',
          component: () => import(/* webpackChunkName: "home" */ './views/Home.vue'),
        },{
          path: 'mine',
          component: () => import(/* webpackChunkName: "home" */ './views/Home.vue'),
        },
      ]
    }, 
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import(/* webpackChunkName: "about" */ './views/About.vue'),
      meta: {
        requireAuth: true
      },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import(/* webpackChunkName: "register" */ './views/Register.vue'),
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import(/* webpackChunkName: "login" */ './views/Login.vue')
    }
  ],
})

router.beforeEach((to, from, next) => {
  if(to.meta.requireAuth) {
    if(store.state.token) {
      next()
    }else {
      next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      })
    }
  }else {
    next()
  }
})

export default router
